import React from 'react';
import { Modal, Form, DatePicker } from 'antd';
import dayjs from 'dayjs'

class PlanExecDialog extends React.Component {
  constructor(props) {
    super(props);

    this.handleSubmit = this.handleSubmit.bind(this);

    this.formRef = React.createRef();
    this.state = { confirmLoading: false };
  }

  async handleSubmit() {
    try {
      const values = await this.formRef.current.validateFields();

      this.onFinish(values);
    } catch (err) {
      console.log('validateFields error', err);
    }
  }

  async onFinish(values) {
    let from, to;
    if ('date_range' in values) {
      from = values.date_range[0].startOf('day');
      to = values.date_range[1].startOf('day').add(1, 'day');
    } else {
      from = values.date.startOf('day');
      to = from.add(1, 'day');
    }

    const plan = { ...this.props.plan, from, to }

    const result = this.props.onSubmit && this.props.onSubmit(plan);
    if (result instanceof Promise) {
      this.setState({ confirmLoading: true });
      result.finally(() => {
        this.setState({ confirmLoading: false });
      });
    }
  }

  render() {
    const { plan, open, onCancel } = this.props;
    const pickerType = plan.picker_type;
    const initialValues = {};

    let dateItem;
    if (pickerType === 'DATE') {
      initialValues.date = dayjs();

      dateItem = (<Form.Item
        label="时间"
        name="date"
        rules={[
          {
            required: true,
          },
        ]}>
        <DatePicker />
      </Form.Item>);
    } else {
      dateItem = (<Form.Item
        label="时间"
        name="date_range"
        rules={[
          {
            required: true,
          },
        ]}>
        <DatePicker.RangePicker />
      </Form.Item>);
    }

    return (
      <Modal title='请选择时间'
        zIndex={1020}
        open={open}
        confirmLoading={this.state.confirmLoading}
        onCancel={onCancel}
        onOk={this.handleSubmit}>
        <Form
          ref={this.formRef}
          colon={false}
          initialValues={initialValues}>
          {dateItem}
        </Form>
      </Modal>
    )
  }
}

export default PlanExecDialog